<script setup lang="tsx">
import {ref} from "vue";
import {$t} from "@/locales";
import {DataTableColumn, NButton, NDescriptions, NDescriptionsItem, NFormItem, NPopconfirm, NTag} from "naive-ui";
import {useLoading} from "~/packages/hooks";
import {getStorageConfig, saveStorageConfig} from "@/service/api";

const {startLoading, endLoading} = useLoading();

const tableData = ref<Api.Storage.Config[]>();
const columns = ref<DataTableColumn[]>([
  {
    key: 'pluginId',
    title: '存储方式',
  },
  {
    key: 'order',
    title: '排序',
  },
  {
    key: 'isEnabled',
    title: '是否启用',
    render: function (row: Api.Storage.Config | any) {
      return (
        <NTag type={row.isEnabled ? 'success' : 'error'}> {row.isEnabled ? '启用' : '禁用'}</NTag>
      )
    }
  },
  {
    key: 'attributes',
    title: '参数详情',
    render: function (row: Api.Storage.Config | any) {
      return (
        <NDescriptions label-placement="left" column={1} label-style={{fontWeight: 'bold'}}>
          {Object.keys(row.attributes).map((key) => (
            <NDescriptionsItem label={key}>
              {row.attributes[key]}
            </NDescriptionsItem>
          ))}
        </NDescriptions>
      )
    }
  },
  {
    key: 'operate',
    title: $t('common.operate'),
    align: 'center',
    render: function (row: any) {
      return (
        <div class="flex-center gap-8px">
          <NButton type="primary" size="tiny" onClick={() => handleEditConfig(row)}>
            修改
          </NButton>
          <NPopconfirm onPositiveClick={() => editState(row)}>
            {{
              default: () => '确定' + (row.isEnabled ? '禁用' : '启用') + '该存储方式吗?',
              trigger: () => (
                <NButton type="success" ghost size="tiny">
                  {row.isEnabled ? '禁用' : '启用'}
                </NButton>
              )
            }}
          </NPopconfirm>
        </div>
      )
    }
  }
]);
const pagination = ref<Api.Common.Pageable>({
    pageSize: 15,
    pageNumber: 1,
    searchProperty: null,
    searchValue: null,
    orderProperty: null,
    orderDirection: null,
    filters: null
  }
);
const drawerVisible = ref(false);
const currentRow = ref<Api.Storage.Config>();
const formModel = ref({})
const dynamicInputValue = ref([{value: '', name: ''}]);
const handleEditConfig = (data: any) => {
  drawerVisible.value = true;
  dynamicInputValue.value = [];
  Object.keys(data.attributes).map((key) => (
    dynamicInputValue.value.push({
      value: data.attributes[key],
      name: key
    })
  ));
  currentRow.value = data;
}
const editState =async (data: any) => {
  data.isEnabled = !data.isEnabled;
  currentRow.value = data;
  const {error} = await saveStorageConfig(currentRow.value as any);
  if (!error) {
    await getData();
    window.$message?.success('操作成功');
  }
}
async function getData() {
  startLoading();
  let {error, data} = await getStorageConfig(pagination.value);
  if (!error) {
    tableData.value = data?.content;
  }
  endLoading();
}

function addItem() {
  return {
    name: '',
    value: ''
  }
}

async function saveData() {
  if (currentRow.value) {
    currentRow.value.attributes = Object.fromEntries(dynamicInputValue.value.map((item) => [item.name, item.value]));
    const {error} = await saveStorageConfig(currentRow.value as any);
    if (!error) {
      drawerVisible.value = false;
      await getData();
      window.$message?.success('保存成功');
    }
  }

}

getData();
</script>

<template>
  <n-space vertical :size="12">
    <n-data-table
      :bordered="false"
      :single-line="false"
      :columns="columns"
      :data="tableData"
      :pagination="pagination"
    />
  </n-space>
  <n-drawer v-model:show="drawerVisible" :width="650">
    <n-drawer-content>
      <template #header>
        修改参数
      </template>
      <template #default>
        <n-form
          ref="formRef"
          :model="formModel"
          label-placement="left"
          label-width="auto"
          size="small"
        >
          <n-dynamic-input v-model:value="dynamicInputValue" item-style="margin-bottom: 0;" #="{ index }"
                           :on-create="addItem">
            <div style="display: flex">
              <!--
                通常，path 的变化会导致 form-item 验证内容或规则的改变，所以 naive-ui 会清理掉
                表项已有的验证信息。但是这个例子是个特殊情况，我们明确的知道，path 的改变不会导致
                form-item 验证内容和规则的变化，所以就 ignore-path-change
              -->
              <n-form-item
                ignore-path-change
                :show-label="false"
                :path="`dynamicInputValue[${index}].name`"
              >
                <n-input
                  v-model:value="dynamicInputValue[index].name"
                  placeholder=""
                  size="medium"
                  @keydown.enter.prevent
                />
              </n-form-item>
              <div style="height: 34px; line-height: 34px; margin: 0 8px">：</div>
              <n-form-item
                ignore-path-change
                :show-label="false"
                :path="`dynamicInputValue[${index}].value`"
              >
                <n-input
                  v-model:value="dynamicInputValue[index].value"
                  style="width: 380px"
                  size="medium"
                  placeholder=""
                  @keydown.enter.prevent
                />
              </n-form-item>
            </div>
          </n-dynamic-input>
        </n-form>
      </template>
      <template #footer>
        <n-button type="primary" @click="saveData">保存</n-button>
      </template>
    </n-drawer-content>
  </n-drawer>
</template>

<style scoped>

</style>
